/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.property.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.common.collect.Lists;
import me.zhengjie.modules.property.domain.Property1;
import me.zhengjie.modules.property.service.dto.Property1Dto;
import me.zhengjie.modules.utils.utils.DateUtils;
import me.zhengjie.modules.utils.DownExcelTemp;
import me.zhengjie.modules.utils.DownLoadUtil;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.property.repository.Property1Repository;
import me.zhengjie.modules.property.service.Property1Service;
import me.zhengjie.modules.property.service.dto.Property1QueryCriteria;
import me.zhengjie.modules.property.service.mapstruct.Property1Mapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.sql.Date;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author yyj
* @date 2021-10-01
**/
@Service
@RequiredArgsConstructor
public class Property1ServiceImpl implements Property1Service {

    private final Property1Repository propertyRepository;
    private final Property1Mapper propertyMapper;


    private static String warningInfo = "带*号的列请选择下拉框内的数据，红色字体为必填项";

    @Override
    public Map<String,Object> queryAll(Property1QueryCriteria criteria, Pageable pageable){
        Page<Property1> page = propertyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(propertyMapper::toDto));
    }

    @Override
    public List<Property1Dto> queryAll(Property1QueryCriteria criteria){
        return propertyMapper.toDto(propertyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public Property1Dto findById(Integer id) {
        Property1 property = propertyRepository.findById(id).orElseGet(Property1::new);
        ValidationUtil.isNull(property.getId(),"Property1","id",id);
        return propertyMapper.toDto(property);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Property1Dto create(Property1 resources) {
        return propertyMapper.toDto(propertyRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Property1 resources) {

        Property1 property = propertyRepository.findById(resources.getId()).orElseGet(Property1::new);
        ValidationUtil.isNull( property.getId(),"Property1","id",resources.getId());
        property.copy(resources);
        propertyRepository.save(property);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            propertyRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<Property1Dto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Property1Dto property : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", property.getName());
            map.put("金钱", property.getPrice());
            map.put("创建日期", property.getCreateTime());
            map.put("更新日期", property.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }



    public long propertyNum() {
        return propertyRepository.count();
    }

    @Override
    public void exportTemplate(HttpServletResponse response) throws IOException {
        //将虚拟路径转换物理路径
        String newFilePath = System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
        //模板名称
        String fileName = "信息模板";
        //设置头
        String[] headers = {"名称", "数量", "附件", "创建时间"};
        Integer[] mandatory = {0, 1, 2, 4, 5, 10};
        List<String> headerList = new ArrayList<>();
        for (int i = 0; i < headers.length; i++) {
            headerList.add(headers[i]);
        }
        //存放数据集
        List<List<String>> downData = new ArrayList<>();
        //数据所在列
        List<String> downRows = Lists.newArrayList();
        downRows.add("0");
        downRows.add("2");
        downRows.add("3");
        //生成待下载excel模板
        DownExcelTemp.createExcelTemplate(newFilePath, fileName, headerList, downData, downRows, mandatory, warningInfo);
        //下载模板
        DownLoadUtil.downFile(newFilePath, fileName, response);
        //删除临时文件
        File delFile = new File(newFilePath);
        if (delFile.exists()) {
            delFile.delete();
        }
    }

    @Override
    public Map<String,Object> upload(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        try {
            ExcelReader reader;
            reader = ExcelUtil.getReader(file.getInputStream());
            reader.addHeaderAlias("名称", "name");
            reader.addHeaderAlias("数量", "price");
            reader.addHeaderAlias("附件", "fileName");
            reader.addHeaderAlias("创建日期", "createTime");

            List<Property1> list = reader.readAll(Property1.class);
            List<Property1> result = new ArrayList<>();
            list.remove(0);

            for (Property1 property : list) {
               result.add(property);
            }
//            result.add((Property1) list);
//            result.add(list);
            propertyRepository.saveAll(result);
            map.put("state", "success");
            map.put("info", "导入" + list.size() + "条数据，成功" + result.size() + "条");

    } catch (IOException e) {
            map.put("state", "error");
            map.put("message", "导入失败");
        }
        return map;
    }



    public Map<String,Object> importFile(MultipartFile file){

        Map<String,Object> map = new HashMap<>();



        map.put("state","error");
        map.put("message","导入失败");
        return map;
    }



    public long querySum(Date dateOne){

        return propertyRepository.querySum(dateOne);
    }

    @Override
    public List<Map<Object, Object>> number() {
        long num=0;
        List <String> list = new ArrayList<>();
        List <Map<Object,Object>> dateList = new ArrayList<>();
        list=DateUtils.dateArr();
        for (int i = 0; i < list.size(); i++) {
            num=propertyRepository.number(list.get(i));
            Map<Object, Object> map = new HashMap<>();
            map.put("date",list.get(i));
            map.put("num",num);
            dateList.add(map);
        }
        return dateList;
    }

    @Override
    public Integer getPrice() {
      return null;
    }

    public List<Map<Object, Object>> number1() {
        List <String> list = new ArrayList<>();
        List <Map<Object,Object>> dateList = new ArrayList<>();

        list=DateUtils.dateArr();
        dateList=propertyRepository.number1(list);

        return dateList;
    }



    public Map<Object,Object> sumProperty(Date dateOne){

        long num=propertyRepository.querySum(dateOne);
        Date date=dateOne;
        Map<Object, Object> map = new HashMap<>();
        map.put(date,num);

        return map;

    }
}